package com.happyface.itemtouchhelper;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by hxm on 2017/5/11.
 * 描述：
 */
public class ModuleSortAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements ItemTouchHelperAdapter {

    public static final int TYPE_TITLE = 0;//普通标题
    public static final int TYPE_EDIT = 1;//编辑
    public static final int TYPE_SORT = 2;//最新发布，最新回复
    public static final int TYPE_MY_MODULE = 3;//我的板块
    public static final int TYPE_MORE_MODULE = 4;//更多板块
    private int headerBeforeMine = 3;//我的板块之前的item数量
    private int headerBeforeMore = 4;//更多板块之前的item数量
    private Handler delayHandler = new Handler();
    private ItemTouchHelper itemTouchHelper;
    private Context context;
    private List<ModuleData.ModuleInfo> myModuleList;
    private List<ModuleData.ModuleInfo> moreModuleList;
    private ModuleData moduleData;
    private RecyclerView recyclerView;
    private boolean isEditMode = false;//是否处于编辑状态
    private OnItemClickListener listener;
    private SortClickListener sortListener;
    private int selectId;//帖子排序，0最新回复，1最新发布(默认)

    public ModuleSortAdapter(Context context, ModuleData data, int selectId, ItemTouchHelper itemTouchHelper) {
        this.itemTouchHelper = itemTouchHelper;
        this.context = context;
        this.moduleData = data;
        this.myModuleList = data.getUser_model_list();
        this.moreModuleList = data.getMore_model_list();
        this.selectId = selectId;
        moduleData.setEdit(false);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        recyclerView = (RecyclerView) parent;
        switch (viewType) {
            case TYPE_TITLE:
                view = LayoutInflater.from(context).inflate(R.layout.h_item_module_title, parent, false);
                return new TitleHolder(view);
            case TYPE_EDIT:
                view = LayoutInflater.from(context).inflate(R.layout.h_item_module_edit, parent, false);
                return new EditHolder(view);
            case TYPE_SORT:
                view = LayoutInflater.from(context).inflate(R.layout.h_item_module_sort, parent, false);
                return new SortHolder(view);
            case TYPE_MY_MODULE:
                view = LayoutInflater.from(context).inflate(R.layout.h_item_my_module, parent, false);
                return new MyModuleHolder(view);
            default:
                view = LayoutInflater.from(context).inflate(R.layout.h_item_more_module, parent, false);
                return new MoreModuleHolder(view);
        }

    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        int type = holder.getItemViewType();
        switch (type) {
            case TYPE_TITLE:
                final TitleHolder titleHolder = (TitleHolder) holder;
                if (position == 0) {
                    titleHolder.tvTitleOne.setText("帖子排序");
                }
                if (position == myModuleList.size() + headerBeforeMine) {
                    titleHolder.tvTitleOne.setText("更多板块");
                }
                break;
            case TYPE_EDIT:
                final EditHolder editHolder = (EditHolder) holder;
                editHolder.tvTitleOne.setText("我的板块");
                editHolder.tvEdit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isEditMode) {
                            isEditMode = true;
                            editHolder.tvEdit.setText("完成");
                            editHolder.tvEdit.setTextColor(context.getResources().getColor(R.color.btn_red));
                            moduleData.setEdit(isEditMode);
                            notifyDataSetChanged();
                        } else {
                            editHolder.tvEdit.setText("编辑");
                            editHolder.tvEdit.setTextColor(Color.parseColor("#222222"));
                            isEditMode = false;
                            moduleData.setEdit(false);
                            notifyDataSetChanged();
                        }
                    }
                });
                break;
            case TYPE_SORT:
                final SortHolder sortHolder = (SortHolder) holder;
                final TextView tvReply = sortHolder.tvReply;
                final TextView tvPublish = sortHolder.tvPublish;
                if (selectId == 0) {
                    tvReply.setTextColor(Color.parseColor("#ffffff"));
                    tvPublish.setTextColor(Color.parseColor("#222222"));
                    tvReply.setBackgroundResource(R.drawable.h_post_module_red_background);
                    tvPublish.setBackgroundResource(R.drawable.h_post_module_white_background);
                } else {
                    tvReply.setTextColor(Color.parseColor("#222222"));
                    tvPublish.setTextColor(Color.parseColor("#ffffff"));
                    tvReply.setBackgroundResource(R.drawable.h_post_module_white_background);
                    tvPublish.setBackgroundResource(R.drawable.h_post_module_red_background);
                }
                tvReply.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        selectId = 0;
                        if (sortListener != null) {
                            sortListener.onClick(selectId);
                        }
                        tvReply.setTextColor(Color.parseColor("#ffffff"));
                        tvPublish.setTextColor(Color.parseColor("#222222"));
                        tvReply.setBackgroundResource(R.drawable.h_post_module_red_background);
                        tvPublish.setBackgroundResource(R.drawable.h_post_module_white_background);
                    }
                });

                tvPublish.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        selectId = 1;
                        if (sortListener != null) {
                            sortListener.onClick(selectId);
                        }
                        tvReply.setTextColor(Color.parseColor("#222222"));
                        tvPublish.setTextColor(Color.parseColor("#ffffff"));
                        tvReply.setBackgroundResource(R.drawable.h_post_module_white_background);
                        tvPublish.setBackgroundResource(R.drawable.h_post_module_red_background);
                    }
                });
                break;
            case TYPE_MY_MODULE:
                final MyModuleHolder myModuleHolder = (MyModuleHolder) holder;
                int myPosition = position - headerBeforeMine;
                myModuleHolder.tvModuleName.setText(myModuleList.get(myPosition).getModel_name());
                myModuleHolder.tvModuleName.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isEditMode) {
                            removeItemFromMyModule(recyclerView, myModuleHolder);
                        } else {
                            if (listener != null) {
                                listener.onItemClick();
                            }
                        }
                    }
                });
                myModuleHolder.tvModuleName.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        if (!isEditMode) {
                            isEditMode = true;
                            moduleData.setEdit(true);
                            notifyDataSetChanged();
                            View view = recyclerView.getChildAt(2);
                            if (view == recyclerView.getLayoutManager().findViewByPosition(2)) {
                                TextView tvEdit = (TextView) view.findViewById(R.id.tv_edit);
                                tvEdit.setText("完成");
                                tvEdit.setTextColor(context.getResources().getColor(R.color.btn_red));
                            }
                        }
                        itemTouchHelper.startDrag(myModuleHolder);
                        return true;
                    }
                });
                myModuleHolder.tvModuleName.setOnTouchListener(new View.OnTouchListener() {

                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (isEditMode) {
                            switch (MotionEventCompat.getActionMasked(event)) {
                                case MotionEvent.ACTION_MOVE:
                                    itemTouchHelper.startDrag(myModuleHolder);
                                    break;
                            }

                        }
                        return false;
                    }
                });
                if (moduleData.isEdit()) {
                    myModuleHolder.imageView.setVisibility(View.VISIBLE);
                } else {
                    myModuleHolder.imageView.setVisibility(View.INVISIBLE);
                }
                break;
            default:
                final MoreModuleHolder moreModuleHolder = (MoreModuleHolder) holder;
                int morePosition = position - myModuleList.size() - headerBeforeMore;
                moreModuleHolder.tvModuleName.setText(moreModuleList.get(morePosition).getModel_name());
                moreModuleHolder.tvModuleName.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isEditMode) {
                            addItemToMyModule(recyclerView, moreModuleHolder);
                        }
                    }
                });
                if (moduleData.isEdit()) {
                    moreModuleHolder.imageView.setVisibility(View.VISIBLE);
                } else {
                    moreModuleHolder.imageView.setVisibility(View.INVISIBLE);
                }
                break;
        }
    }

    @Override
    public int getItemCount() {
        return myModuleList.size() + moreModuleList.size() + headerBeforeMore;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0 || position == myModuleList.size() + headerBeforeMine) {
            return TYPE_TITLE;
        }
        if (position == 1) {
            return TYPE_SORT;
        }
        if (position == 2) {
            return TYPE_EDIT;
        }
        if (position > 2 && position < myModuleList.size() + headerBeforeMine) {
            return TYPE_MY_MODULE;
        }
        return TYPE_MORE_MODULE;
    }

    @Override
    public void onItemMove(int fromPosition, int toPosition) {
        ModuleData.ModuleInfo myModule = myModuleList.get(fromPosition - headerBeforeMine);
        myModuleList.remove(fromPosition - headerBeforeMine);
        myModuleList.add(toPosition - headerBeforeMine, myModule);
        notifyItemMoved(fromPosition, toPosition);
    }

    @Override
    public void onItemDismiss(int position) {
        //不适用
    }

    //从我的板块移除item,动画存在问题未解决，先注释掉
    private void removeItemFromMyModule(RecyclerView recyclerView, MyModuleHolder holder) {
//        int position = holder.getAdapterPosition();
//        GridLayoutManager manager = (GridLayoutManager) recyclerView.getLayoutManager();
//        View targetView = manager.findViewByPosition(myModuleList.size() + headerBeforeMore);
//        View currentView = manager.findViewByPosition(position);
        //判断targetView是否在屏幕内,不再的话indexOfChild为-1，此时notifyItemMoved自带一个向目标移动的动画
        //若在屏幕内，则添加一个动画过渡
//        if (recyclerView.indexOfChild(targetView) >= 0) {
//            int targetX, targetY;
//            int spanCount = manager.getSpanCount();
//            //我的板块最后一行只有一个item时,移动后高度将变化
//            if ((myModuleList.size() - 1) % spanCount == 0) {
//                View newTargetView = manager.findViewByPosition(myModuleList.size() + headerBeforeMore - 1);
//                targetX = newTargetView.getLeft();
//                targetY = newTargetView.getTop();
//            } else {
//                targetX = targetView.getLeft();
//                targetY = targetView.getTop();
//            }
//            moveMyToMore(holder);
////            startAnimation(recyclerView, currentView, targetX, targetY);
//        } else {
        moveMyToMore(holder);
//        }
    }

    //从更多板块添加item到我的板块
    private void addItemToMyModule(RecyclerView recyclerView, MoreModuleHolder holder) {
//        GridLayoutManager manager = (GridLayoutManager) recyclerView.getLayoutManager();
//        int currentPosition = holder.getAdapterPosition();
//        //我的板块中最后一个item
//        int finalPosition = myModuleList.size() + headerBeforeMine - 1;
//        View preTargetView = manager.findViewByPosition(finalPosition);
//        View currentView = manager.findViewByPosition(currentPosition);
//        if (recyclerView.indexOfChild(preTargetView) >= 0) {
//            int targetX = preTargetView.getLeft();
//            int targetY = preTargetView.getTop();
//            int targetPosition = finalPosition + 1;
//            int spanCount = manager.getSpanCount();
//            //targetView在最后一行第一个
//            if ((targetPosition - headerBeforeMine) % spanCount == 0) {
//                View targetView = manager.findViewByPosition(targetPosition);
//                targetX = targetView.getLeft();
//                targetY = targetView.getTop();
//            } else {
//                targetX += preTargetView.getWidth();
//                //最后的item可见
//                if (manager.findLastVisibleItemPosition() == getItemCount() - 1) {
//                    //最后一个item在最后一行第一个位置
//                    if (getItemCount() - myModuleList.size() - headerBeforeMore - 1 % spanCount == 0) {
//                        // RecyclerView实际高度 > 屏幕高度 && RecyclerView实际高度 < 屏幕高度 + item.height
//                        int firstVisiblePosition = manager.findFirstVisibleItemPosition();
//                        if (firstVisiblePosition == 0) {
//                            // FirstCompletelyVisibleItemPosition == 0 即 内容不满一屏幕 , targetY值不需要变化
//                            // FirstCompletelyVisibleItemPosition != 0 即 内容满一屏幕 并且 可滑动 , targetY值 + firstItem.getTop
//                            if (manager.findFirstCompletelyVisibleItemPosition() != 0) {
//                                int offset = (-recyclerView.getChildAt(0).getTop()) - recyclerView.getPaddingTop();
//                                targetY += offset;
//                            }
//                        } else {
//                            // 在这种情况下,RecyclerView高度变化时(即可见第一个item的 position != 0),
//                            // 移动后, targetY值  + 一个item的高度
//                            targetY += preTargetView.getHeight();
//                        }
//                    }
//                }
//            }
//            // 如果当前位置是“更多板块”可见的最后一个，且当前位置不在grid的第一个位置，目标位置不在grid的第一个位置
//            // 则需要延迟250秒 notifyItemMove,因为这种情况,并不触发ItemAnimator,会直接刷新界面
//            // 导致我们的位移动画刚开始,就已经notify完毕,引起不同步问题
//            if (currentPosition == manager.findLastVisibleItemPosition()
//                    && (currentPosition - myModuleList.size() - headerBeforeMore) % spanCount != 0
//                    && (targetPosition - headerBeforeMine) % spanCount != 0) {
//                moveMoreToMy(holder, true);
//            } else {
//                moveMoreToMy(holder, false);
//            }
//            startAnimation(recyclerView, currentView, targetX, targetY);
//        } else {
        moveMoreToMy(holder, false);
//        }

    }

    /**
     * 从我的板块移动到更多板块
     *
     * @param holder
     */
    private void moveMyToMore(MyModuleHolder holder) {
        int position = holder.getAdapterPosition();
        int startIndex = position - headerBeforeMine;
        if (startIndex > myModuleList.size() - 1) {
            return;
        }
        ModuleData.ModuleInfo moreModule = myModuleList.get(startIndex);
        myModuleList.remove(startIndex);
        moreModuleList.add(0, moreModule);
        notifyItemMoved(position, myModuleList.size() + headerBeforeMore);
    }

    /**
     * 从更多板块移动到我的板块
     *
     * @param holder
     * @param isDelay
     */
    private void moveMoreToMy(MoreModuleHolder holder, boolean isDelay) {
        final int position = holder.getAdapterPosition();
        int startIndex = position - myModuleList.size() - headerBeforeMore;
        if (startIndex > moreModuleList.size() - 1) {
            return;
        }
        ModuleData.ModuleInfo moreModule = moreModuleList.get(startIndex);
        moreModuleList.remove(startIndex);
        myModuleList.add(moreModule);
        if (isDelay) {
            delayHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    notifyItemMoved(position, myModuleList.size() + headerBeforeMine - 1);
                }
            }, 360);
        } else {
            notifyItemMoved(position, myModuleList.size() + headerBeforeMine - 1);
        }
    }

    /**
     * 开始增删动画
     */
    private void startAnimation(RecyclerView recyclerView, final View currentView, float targetX, float targetY) {
        final ViewGroup viewGroup = (ViewGroup) recyclerView.getParent();
        final ImageView mirrorView = addMirrorView(viewGroup, recyclerView, currentView);
        float endX = targetX - currentView.getLeft();
        float endY = targetY - currentView.getTop();
        Animation animation = getTranslateAnimation(endX, endY);
        currentView.setVisibility(View.INVISIBLE);
        mirrorView.startAnimation(animation);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                viewGroup.removeView(mirrorView);
                if (currentView.getVisibility() == View.INVISIBLE) {
                    currentView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    /**
     * 获取位移动画
     */
    private TranslateAnimation getTranslateAnimation(float targetX, float targetY) {
        TranslateAnimation translateAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.ABSOLUTE, targetX,
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.ABSOLUTE, targetY);
        // RecyclerView默认移动动画250ms 这里设置360ms 是为了防止在位移动画结束后 remove(view)过早 导致闪烁
        translateAnimation.setDuration(360);
        translateAnimation.setFillAfter(true);
        return translateAnimation;
    }

    /**
     * 添加需要移动的 镜像View
     */
    private ImageView addMirrorView(ViewGroup parent, RecyclerView recyclerView, View view) {
        /**
         * 1、通过setDrawingCacheEnable方法开启cache；
         * 2、调用getDrawingCache方法就可以获得view的cache图片。buildDrawingCache方法可以不用调用，
         * 因为调用getDrawingCache方法时，若果cache没有建立，系统会自动调用buildDrawingCache方法生成cache。
         * 当调用setDrawingCacheEnabled方法设置为false, 系统也会自动把原来的cache销毁。
         */
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(true);
        final ImageView mirrorView = new ImageView(recyclerView.getContext());
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        mirrorView.setImageBitmap(bitmap);
        view.setDrawingCacheEnabled(false);
        int[] locations = new int[2];
        view.getLocationOnScreen(locations);
        int[] parenLocations = new int[2];
        recyclerView.getLocationOnScreen(parenLocations);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(bitmap.getWidth(), bitmap.getHeight());
        params.setMargins(locations[0], locations[1] - parenLocations[1], 0, 0);
        parent.addView(mirrorView, params);

        return mirrorView;
    }

    public void setOnSortClickListener(SortClickListener listener) {
        this.sortListener = listener;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public interface SortClickListener {
        void onClick(int selectId);
    }

    public interface OnItemClickListener {
        void onItemClick();
    }

    private static class MyModuleHolder extends RecyclerView.ViewHolder implements ItemTouchHelperViewHolder {
        private TextView tvModuleName;
        private ImageView imageView;

        MyModuleHolder(View itemView) {
            super(itemView);
            tvModuleName = (TextView) itemView.findViewById(R.id.tv_module);
            imageView = (ImageView) itemView.findViewById(R.id.iv_delete);
        }

        @Override
        public void onItemSelected() {

        }

        @Override
        public void onItemClear() {

        }
    }

    private static class MoreModuleHolder extends RecyclerView.ViewHolder implements ItemTouchHelperViewHolder {
        private TextView tvModuleName;
        private ImageView imageView;

        public MoreModuleHolder(View itemView) {
            super(itemView);
            tvModuleName = (TextView) itemView.findViewById(R.id.tv_module);
            imageView = (ImageView) itemView.findViewById(R.id.iv_add);
        }

        @Override
        public void onItemSelected() {

        }

        @Override
        public void onItemClear() {

        }
    }

    private static class TitleHolder extends RecyclerView.ViewHolder {
        private TextView tvTitleOne;

        TitleHolder(View itemView) {
            super(itemView);
            tvTitleOne = (TextView) itemView.findViewById(R.id.tv_title_one);
        }
    }

    private static class EditHolder extends RecyclerView.ViewHolder {
        private TextView tvTitleOne;
        private TextView tvEdit;

        EditHolder(View itemView) {
            super(itemView);
            tvTitleOne = (TextView) itemView.findViewById(R.id.tv_title_one);
            tvEdit = (TextView) itemView.findViewById(R.id.tv_edit);
        }
    }

    private static class SortHolder extends RecyclerView.ViewHolder {
        private TextView tvReply, tvPublish;

        SortHolder(View itemView) {
            super(itemView);
            tvReply = (TextView) itemView.findViewById(R.id.tv_reply);
            tvPublish = (TextView) itemView.findViewById(R.id.tv_publish);
        }
    }
}
